package com.gaogzhen.juc.atomic.Reference;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicMarkableReference;

/**
 * 更换垃圾袋
 */
@Slf4j(topic = "c.ReplaceGarbageBag")
public class ReplaceGarbageBag {
    public static void main(String[] args) throws InterruptedException {
        GarbageBag bag = new GarbageBag("满的垃圾袋");
        // true表示垃圾袋已满，false为空
        AtomicMarkableReference<GarbageBag> ref = new AtomicMarkableReference<>(bag, true);
        log.debug("start ...");
        GarbageBag prev = ref.getReference();
        log.debug(prev.toString());
         new Thread(() -> {
            log.debug("start...");
            bag.setDesc("空的垃圾袋");
            ref.compareAndSet(bag, bag, true, false);
            log.debug(bag.toString());
         }, "保洁阿姨").start();
        TimeUnit.SECONDS.sleep(1);
        log.debug("换一个空的垃圾袋？");
        boolean success = ref.compareAndSet(prev, new GarbageBag("空的垃圾袋"), true, false);
        log.debug("更换了吗？{}", success);
        log.debug(ref.getReference().toString());
    }
}
